package hello.lib;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

/**
 * 模拟电视屏幕
 */
public class TVScreen extends JPanel{
    private int scale;
    private int screenWidth;
    private int screenHeight;

    private BufferedImage bufferedImage1 ;
    private BufferedImage bufferedImage2 ;

    private boolean image1NeedDraw = false;//是否使用1号绘制

    //JFrame frame;

    public TVScreen(int scale, int screenWidth, int screenHeight) {
        this.scale = scale;
        this.screenWidth = screenWidth;
        this.screenHeight = screenHeight;
        bufferedImage1 = new BufferedImage(screenWidth*scale, screenHeight*scale, BufferedImage.TYPE_INT_RGB);
        bufferedImage2 = new BufferedImage(screenWidth*scale, screenHeight*scale, BufferedImage.TYPE_INT_RGB);
    }
    @Override
    public void paint(Graphics g) {
        if (image1NeedDraw){
            g.drawImage(bufferedImage1, 0, 0, null);
        }else{
          g.drawImage(bufferedImage2, 0, 0, null);
        }
        //System.out.println(image1NeedDraw);
    }

    public void reset(int scale, int screenWidth, int screenHeight){
        this.scale = scale;
        this.screenWidth = screenWidth;
        this.screenHeight = screenHeight;
        bufferedImage1 = new BufferedImage(screenWidth*scale, screenHeight*scale, BufferedImage.TYPE_INT_RGB);
        bufferedImage2 = new BufferedImage(screenWidth*scale, screenHeight*scale, BufferedImage.TYPE_INT_RGB);
    }

    public void setPixel(int x,int y,Color color){
        Graphics2D g = image1NeedDraw ? bufferedImage2.createGraphics() : bufferedImage1.createGraphics();
        g.setColor(color);
        g.fillRect(x*scale, y*scale, scale, scale);
    }

    public void repaint(){
        image1NeedDraw = !image1NeedDraw;
        super.repaint();
    }
}
